import React, { useRef, useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Button, message, Space, Table, Input, Tag ,Divider } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined ,EyeOutlined} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { apipage, apiDelete } from '@/services/system/apimanage';
import { useOutletContext } from '@umijs/max';
import AuthorizedButton from '@/components/AuthorizedButton';
import { useModel } from '@umijs/max';
interface ButtonData {
  id: string;
  pageId: string;
  resourceName: string;
  icon?: string;
  action: string;
}
const ApiManageList: React.FC = () => {
  const [records, setRecords] = useState<any[]>([]);
  const { buttonData } = useOutletContext<{ buttonData: ButtonData[] }>();
  const { institutionId } = useModel('auth');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const navigate = useNavigate();

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async (params = {}) => {
    try {
      const response = await apipage({
        current: params?.current || 1,
        size: params?.pageSize || 10,
        ...params,
        institutionId
      });
      if (response.code === 200) {
        console.log('response.data', response.data);
        setRecords(response.data);
        setPagination({
          current: response.data.current,
          pageSize: response.data.size,
          total: response.data.total,
        });
      }
    } catch (error) {
      console.error(error);
    }
  };

  const getScopeType = (type: string) => {
    const typeMap: Record<string, { text: string; color: string }> = {
      '1': { text: 'GET', color: 'green' },
      '2': { text: 'POST', color: 'blue' },

    };
    return typeMap[type] || { text: type, color: 'default' };
  };

  const getStatusText = (status: number) => {
    const statusMap: Record<number, { text: string; color: string }> = {
      0: { text: '正常', color: 'success' },
      1: { text: '禁用', color: 'error' },
    };
    return statusMap[status] || { text: '未知', color: 'default' };
  };

  const columns = [
    {
      title: '编号',
      dataIndex: 'id',
      width: 80,
    },
    {
      title: '机构名称',
      dataIndex: 'institutionName',
      width: 150,
    },
    {
      title: '统一社会信用代码',
      dataIndex: 'creditCode',
      width: 180,
    },
    {
      title: '法人代表',
      dataIndex: 'legalRepresentative',
      width: 120,
    },
    {
      title: '法人电话',
      dataIndex: 'legalRepresentativePhone',
      width: 130,
    },
    {
      title: '经办人',
      dataIndex: 'attentionLine',
      width: 120,
    },
    {
      title: '经办人电话',
      dataIndex: 'attentionLinePhone',
      width: 130,
    },
    {
      title: '认证状态',
      dataIndex: 'authenticationStatus',
      width: 100,
      render: (status: number) => {
        const statusMap = {
          0: { text: '未认证', color: 'warning' },
          1: { text: '已认证', color: 'success' },
        };
        const { text, color } = statusMap[status] || { text: '未知', color: 'default' };
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '授信额度',
      dataIndex: 'creditLimit',
      width: 120,
      render: (value: number) => `¥${value?.toLocaleString() || 0}`,
    },
    {
      title: '总授信额度',
      dataIndex: 'allCreditLimit',
      width: 120,
      render: (value: number) => `¥${value?.toLocaleString() || 0}`,
    },
    {
      title: '机构状态',
      dataIndex: 'status',
      width: 100,
      render: (status: number) => {
        const statusMap = {
          0: { text: '正常', color: 'success' },
          1: { text: '停用', color: 'error' },
        };
        const { text, color } = statusMap[status] || { text: '未知', color: 'default' };
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 160,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      width: 160,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 180,
      render: (_: any, record: any) => (
        <span>
          <Space split={<Divider type="vertical" />}>
            <AuthorizedButton
              buttonData={buttonData}
              action="edit"
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
              style={{
                padding: 0,
                height: '22px',
                lineHeight: '22px',
              }}
            >
              编辑
            </AuthorizedButton>
            <AuthorizedButton
              buttonData={buttonData}
              action="delete"
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
              onClick={() => handleDelete(record)}
              style={{
                padding: 0,
                height: '22px',
                lineHeight: '22px',
              }}
            >
              删除
            </AuthorizedButton>
            <AuthorizedButton
              buttonData={buttonData}
              action="view"
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleView(record)}
              style={{
                padding: 0,
                height: '22px',
                lineHeight: '22px',
              }}
            >
              详情
            </AuthorizedButton>
          </Space>
        </span>
      ),
    },
  ];

  const handleAdd = () => {
    navigate('/system/apimanage/add');
  };

  const handleEdit = (record) => {
    navigate('/system/apimanage/edit', { state: { record } });
  };

  const handleDelete = async (record) => {
    try {
      const response = await apiDelete({ institutionId: record.institutionId });
      if (response.code === 200) {
        message.success('删除成功');
        fetchData();
      } else {
        message.error(response.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  const handleView = (record) => {
    navigate('/system/apimanage/view', { state: { record } });
  };

  return (
    <PageContainer>
      <Space style={{ marginBottom: 16 }}>
      <AuthorizedButton
          buttonData={buttonData}
          action="add"
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleAdd}
        >
          新增
        </AuthorizedButton>
      </Space>
      <Table
        columns={columns}
        dataSource={records}
        scroll={{ x: 1800 }}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
          onChange: (page, pageSize) => {
            fetchData({ current: page, size: pageSize });
          },
        }}
      />
    </PageContainer>
  );
};

export default ApiManageList;
